<?php

function Action($controllerName, $actionName = null, $params = null)
{
	if (class_exists($controllerName, true))
	{
		$controller = new $controllerName($params);
		
		if (!$actionName)
		{
			$actionName = "Index";
		}
		
		if (is_callable(array($controller, $actionName)))
		{
			return call_user_func(array($controller, $actionName));
		}
	}
	
	return NotFound();
}

function View()
{
	$viewName = "";
	$stack = debug_backtrace();
	$args = func_get_args();
	
	$controllerName = str_replace("Controller", "", $stack[1]['class']);
	$actionName = $stack[1]['function'];
	
	if (is_string($args[0]))
	{
		$actionName = $args[0];
		$params = $args[1];
	}
	else
	{
		$params = $args[0];
	}
	
	$viewName = "{$controllerName}_{$actionName}View";
	
	if (class_exists($viewName, true) || DEV_SERVER)
	{
		$view = new $viewName($params);

		ob_start();

		$view->Render();

		ob_end_flush();
	}
	else
	{
		NotFound();
	}
}

function PartialView()
{
	$viewName = "{$arg[0]}PartialView";
	
	if (class_exists($viewName, true) || DEV_SERVER)
	{
		$view = new $viewName($arg[1]);

		ob_start();

		$view->Render();

		ob_end_flush();
	}
}

function NotFound()
{
	Action("NotFound", "Index");
}

function memory()
{
	echo "memory usage:".(memory_get_usage())."B\n";
}

function config_set($k, $v)
{
	global $site_config;
	
	if (!is_array($site_config)) $site_config = array();
	
	$site_config[$k] = $v;
}

function config_get($k)
{
	global $site_config;
	
	if (!is_array($site_config)) $site_config = array();
	
	return @$site_config[$k];
}

function str_ends_with($needle, $haystack)
{
	if (!is_array($needle)) $needle = array($needle);
	
	foreach ($needle as $n)
	{
		if (substr($haystack, strlen($haystack) - strlen($n), strlen($n)) == $n) return true;
	}
	
	return false;
}

function ln($str)
{
	echo $str."\n";
}

function minimize_str($str)
{
	return preg_replace('/\s*{\s*/', '{',
				preg_replace('/\s*}\s*/', '}',
					preg_replace('/\s*,\s*/', ',',
						preg_replace('/\s*;\s*/', ';',
							preg_replace('/\s*:\s*/', ':', $str)
						)
					)
				)
			 );
}

?>
